import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;

public class Parser{
	
    public static void main(String[] args){
    	
    	createFromAirports();
    	
    }
    
    
    public static void createFromAirports(){
    	
		try {
    	
    	
		/*	Sets up a file reader to read the file passed on the command
			line one character at a time */
		//FileReader input = new FileReader(args[0]);
    	//FileReader input = new FileReader("GlobalAirportDatabase.txt");
    	FileReader input = new FileReader("airports.dat");
        
		/* Filter FileReader through a Buffered read to read a line at a
		   time */
		BufferedReader bufRead = new BufferedReader(input);
		
        String line; 	// String that holds current file line
        int count = 0;	// Line number of count 
        
        // Read first line
        line = bufRead.readLine();
        count++;
        
        
        PrintWriter pw = new PrintWriter("database_schema_new.txt");
        pw.println("DROP TABLE airport;");
        pw.println("CREATE TABLE airport (iata TEXT, airport_name TEXT, city TEXT, country TEXT, latitude INTEGER, longitude INTEGER, runway INTEGER, passengers INTEGER);");
        
		// Read through file one line at time. Print line # and line
        while (line != null){
        	if (!line.contains("N/A"));{
        		
        		Airport currentAirport = parseAirport(line);
        		if (currentAirport != null) {
        			System.out.println(currentAirport.databaseString());
        			pw.println(currentAirport.databaseString());
        		}
        		else {
        			System.out.println("Null airport");
        		}
        		
        		line = bufRead.readLine();
                count++;
        	}            	
        }
        
        bufRead.close();
        pw.close();
        
		
    }catch (ArrayIndexOutOfBoundsException e){
        /* If no file was passed on the command line, this expception is
		generated. A message indicating how to the class should be
		called is displayed */
		System.out.println("Usage: java ReadFile filename\n");			

	}catch (IOException e){
		// If another exception is generated, print a stack trace
        e.printStackTrace();
    }
    
    }// end main
	
    public static Airport parseAirport(String originalLine){
    	
    	Airport airport = new Airport();
    	//String airportCode = originalLine.substring(0,4);
    	
    	// get from original string
    	int item = 0;
    	int currentCharCount = 0;
    	char currentChar;
    	String word = "";
    	
    	for (; currentCharCount < originalLine.length(); currentCharCount++){
    		
    		currentChar = originalLine.charAt(currentCharCount);
    		
    		if (currentChar == ',' || currentChar == '\n'){
    			if (word.equals("\"\"") || word.equals("\\N")){
        			return null;
        		}
    			switch (item){
    			case 0:																	break;
    			case 1:	airport.setName(word.substring(1,word.length()-1));				break;
    			case 2:	airport.setCity(word.substring(1,word.length()-1));				break;
    			case 3:	airport.setCountry(word.substring(1,word.length()-1));			break;
    			case 4:																	break;
    			case 5:	airport.setIcao(word.substring(1,word.length()-1));				break;
    			case 6:	airport.setLatitude((int)((Float.parseFloat(word))*100000));	break;
    			case 7:	airport.setLongitude((int)((Float.parseFloat(word))*100000));	break;
    			case 8:	airport.setAltitude(Integer.parseInt(word));					break;
    			case 9:	airport.setTimezone(Float.parseFloat(word));					break;
    			case 10: airport.setDst_zone(word.charAt(1));							break;
    			default:																break;
    			}
    			word = "";
    			item++;
    		}
    		else {
    			word += currentChar;
    		}
    		currentChar ++;    		
    	}
    	
    	airport.setRunway(longestRunway(airport.getIcao()));
    	airport.setPassengers(totalPassengers(airport.getIcao()));
    	    	  	    	    	
    	return airport;
    	
    }
       
    
    public static int longestRunway(String airportICAO){
    	
    	String line = null;
    	int longestRunway = 0;
    	
    	try {
            URL url = new URL("http://airports.palzkill.de/details/" + airportICAO + "/runways");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            while ((line = reader.readLine()) != null) {
                if (line.contains("Length:") && !line.contains("rwylength")){
                	line = line.trim();
                	int runway = Integer.parseInt(line.substring(24, line.length()-11));
                	if (runway > longestRunway) longestRunway = runway;
                }
            }
            reader.close();

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
    	
        return longestRunway;
    	
    }
    
    
    public static int totalPassengers(String airportICAO){
    	
    	String line = null;
    	int pax = 0;
    	
    	try {
            URL url = new URL("http://airports.palzkill.de/details/" + airportICAO);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            while ((line = reader.readLine()) != null) {
            	 if (line.contains("Passengers Total")){
            		 boolean paxFound = false;
            		 for (int i = 0; i < 10 && paxFound == false; i++){
            			 line = reader.readLine();
            			 if (line.contains("tablecell_count")){
            				 paxFound = true;
            				 line = line.trim();
            				 String paxLine1 = line.substring(28, line.length()-5);
                         	 String paxLine2 = "";
                         	 for (int j = 0; j < paxLine1.length(); j++){
                         		if (paxLine1.charAt(j) != ','){
                         			paxLine2 += paxLine1.charAt(j);
                         		}
                         	 }
                         	 pax = Integer.parseInt(paxLine2);
            			}
            		}
                }
            }
            reader.close();

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
    	
        return pax;
    	
    }
    
    
    private static int latOrLon(String airportICAO, String latOrlon){
    	
    	String line = null;
    	int latitude = 0;
    	
    	try {
            URL url = new URL("http://airports.palzkill.de/details/" + airportICAO);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            while ((line = reader.readLine()) != null) {
            	 if (line.contains("airport_center_" + latOrlon)){
            		 line = line.trim();
            		 line = line.substring(23,line.length()-1);            		 
            		 Float latitudeF = Float.parseFloat(line);
            		 latitude = (int) (latitudeF * 1000000);
                }
            }
            reader.close();

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
    	
        return latitude;
    	
    }
    
    public static int latitude(String airportICAO){
    	return latOrLon(airportICAO, "lat");
    }
    
    public static int longitude(String airportICAO){
    	return latOrLon(airportICAO, "lon");
    }
    
    
    private static String country(String airportICAO){
    	
    	String line = null;
    	String country = "none";
    	
    	try {
            URL url = new URL("http://airports.palzkill.de/details/" + airportICAO);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            while ((line = reader.readLine()) != null) {
            	 if (line.contains("Country Flag")){
            		 line = line.trim();
            		 //line = line.substring(23,line.length()-1);            		 
            		 //Float latitudeF = Float.parseFloat(line);
            		 //country = (int) (latitudeF * 1000000);
                }
            }
            reader.close();

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
    	
        return country;
    	
    }

}
